/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LookupPanel.java
 *
 * Created on Mar 1, 2013, 1:29:41 PM
 */
package edu.ncsu.csc573.project1.gui;

import edu.ncsu.csc573.project1.peer.DownloadClient;
import edu.ncsu.csc573.project1.peer.Peer;
import edu.ncsu.csc573.project1.util.PeerData;
import java.util.LinkedList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author user
 */
public class LookupPanel extends javax.swing.JPanel {
    Peer peer;
    /** Creates new form LookupPanel */
    public LookupPanel(Peer peer) {
        this.peer = peer;
        initComponents();
        listSelectionModel = this.rfcLookupTable.getSelectionModel();
        listSelectionModel.addListSelectionListener(new SharedListSelectionHandler(this));
        this.rfcLookupTable.setSelectionModel(listSelectionModel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        rfcNumberField = new javax.swing.JTextField();
        rfcTitleField = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        rfcLookupTable = new javax.swing.JTable() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        fetchButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        contentArea = new javax.swing.JTextArea()
        ;

        jLabel1.setText("RFC Number :");

        jLabel2.setText("RFC Title :");

        rfcNumberField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rfcNumberFieldActionPerformed(evt);
            }
        });

        sendButton.setText("Lookup");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        rfcLookupTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null}
            },
            new String [] {
                "Host Name", "Upload Port"
            }
        ));
        jScrollPane1.setViewportView(rfcLookupTable);

        fetchButton.setText("Get RFC");
        fetchButton.setEnabled(false);
        fetchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fetchButtonActionPerformed(evt);
            }
        });

        contentArea.setEditable(false);
        contentArea.setColumns(20);
        contentArea.setRows(5);
        jScrollPane2.setViewportView(contentArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 689, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(21, 21, 21)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rfcTitleField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(rfcNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fetchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(rfcNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(sendButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(rfcTitleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fetchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(28, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void rfcNumberFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rfcNumberFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_rfcNumberFieldActionPerformed

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
        
        if (this.rfcNumberField.getText().equals("")) {
            JOptionPane.showMessageDialog(new JFrame(), "RFC must have a number.", "Lookup Error", JOptionPane.ERROR_MESSAGE);
            return;
        } 
        /*else if (this.rfcTitleField.getText().equals("")) {
            JOptionPane.showMessageDialog(new JFrame(), "RFC must have a title.", "Lookup Error", JOptionPane.ERROR_MESSAGE);
            return;
        }*/
        int rfcNumber = Integer.parseInt(this.rfcNumberField.getText());
        String rfcTitle = "";
        if (this.rfcTitleField.getText().equals("")) {
            rfcTitle = "none";
        } else {
            rfcTitle = this.rfcTitleField.getText();
        }
        
        LinkedList<PeerData> peerData = peer.lookupRfc(rfcNumber, rfcTitle);
        if (peerData == null) {
            this.fetchButton.setEnabled(false);
        }
        
        DefaultTableModel rfcLookupTableModel = (DefaultTableModel)this.rfcLookupTable.getModel();
       
        rfcLookupTableModel.getDataVector().removeAllElements();
        
        if (peerData != null) {
            for (int i = 0; i < peerData.size(); ++i) {
                PeerData currentPeer = peerData.get(i);
                rfcLookupTableModel.addRow(new Object[]{currentPeer.getHostName(), currentPeer.getPortNumber()});
            }
        }
    }//GEN-LAST:event_sendButtonActionPerformed

    private void fetchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fetchButtonActionPerformed
        int selectedIndex = this.rfcLookupTable.getSelectedRow();
        String hostName = this.rfcLookupTable.getValueAt(selectedIndex, 0).toString();
        int portNumber = Integer.valueOf(this.rfcLookupTable.getValueAt(selectedIndex, 1).toString()).intValue();
        DownloadClient client = new DownloadClient(hostName, portNumber);
        String content = client.downloadRfc(Integer.parseInt(this.rfcNumberField.getText()));
        
        contentArea.setEditable(false);        
        contentArea.setText(content);   
        contentArea.setCaretPosition(0);
        client.closeConnection();
    }//GEN-LAST:event_fetchButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea contentArea;
    private javax.swing.JButton fetchButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable rfcLookupTable;
    private javax.swing.JTextField rfcNumberField;
    private javax.swing.JTextField rfcTitleField;
    private javax.swing.JButton sendButton;
    // End of variables declaration//GEN-END:variables
    private javax.swing.ListSelectionModel listSelectionModel;
    
     class SharedListSelectionHandler implements ListSelectionListener {        
        LookupPanel panel;
        public SharedListSelectionHandler(LookupPanel panel) {
            this.panel = panel;           
        }
        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel)e.getSource();
            if (lsm.isSelectionEmpty()) {
            } else {
                int minIndex= lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                for (int i = minIndex; i <= maxIndex; i++) {
                    if (lsm.isSelectedIndex(i)) {
                        panel.fetchButton.setEnabled(true);
                        break;
                    }
                }
            }
        }
    }
}
